import _ from 'lodash';
const simpleBtns = [
   { title: '7', value: '7', action: '' },
   { title: '8', value: '8', action: '' },
   { title: '9', value: '9', action: '' },
   { title: '4', value: '4', action: '' },
   { title: '5', value: '5', action: '' },
   { title: '6', value: '6', action: '' },
   { title: '1', value: '1', action: '' },
   { title: '2', value: '2', action: '' },
   { title: '3', value: '3', action: '' },
   { title: '.', value: '.', action: '' },
   { title: '0', value: '0', action: '' },
   { title: '清空', value: 'clear', action: 'clear' },
];
const extraBtns = [
   { title: '删除', value: 'delete', action: 'delete', order: 3 },
   { title: '+', value: '+', action: 'add', order: 7 },
   { title: '-', value: '-', action: 'subtract', order: 11 },
];

// 特殊字符
const specialCharacters = ['.', '+', '-'];
// 判断最后一个值
const isLastEqual = (str: string, value: string) =>
   str[str.length - 1] === value;
// 判断最后一个值是否为运算符
const isLastOperate = (value: string) =>
   isLastEqual(value, '+') || isLastEqual(value, '-');
// 判断最后一个值是否为数字
const isLastNumber = (value: string) =>
   !specialCharacters.includes(value[value.length - 1]);

const Caculator = ({
   onChange,
   onComplete = undefined,
   data,
   isSimple = false,
}) => {
   const handleSimpleCombine = (value: string, action: string) => {
      if (action === 'clear') {
         onChange('0');
      } else {
         if (data == '0') {
            // 如果本身为0，且新的输入不是0，直接替换
            if (value !== '0') {
               onChange(value);
            } else {
               onChange('0');
            }
         } else {
            onChange(data + value);
         }
      }
   };
   const handleCompute = (value: string, action: string) => {
      if (specialCharacters.includes(value) && isLastEqual(data, value)) return;
      if (value === '.') {
         if (/[.]/.test(data)) return;
         if (isLastOperate(data)) return;
      }
      switch (action) {
         case 'clear':
            onChange('0');
            break;
         case 'delete':
            if (data.length === 1) {
               onChange('0');
            } else {
               onChange(String(data).slice(0, -1));
            }
            break;
         case 'add':
         case 'subtract':
            // 如果最后一个也是运算符 替换掉
            if (isLastOperate(data)) {
               onChange(data.slice(0, -1) + value);
               return;
            }

            // 如果已经存在运算符 且最后一个是数字 运算
            if (isOperate && isLastNumber(data)) {
               onChange(String(eval(data)) + value);
               return;
            }

            onChange(data + value);
            break;
         default:
            if (data.length === 1 && data[0] === '0') {
               onChange(value);
            } else {
               onChange(data + value);
            }

            break;
      }
   };

   const isOperate = /[+-]/.test(data);
   const handleFinish = () => {
      if (isOperate) {
         if (!specialCharacters.includes(data[data.length - 1])) {
            onChange(String(eval(data)));
         }
         return;
      } else {
         onComplete && onComplete('完成');
      }
   };

   // 根据是否为简单版选用不用的计算器
   let outerCls = 'bg-white fixed bottom-0 w-full left-0';
   let layoutCls = 'grid h-full';
   let btns = [];
   let computeFunc = null;
   if (isSimple) {
      btns = simpleBtns;
      computeFunc = handleSimpleCombine;
      layoutCls += ' grid-cols-3';
      outerCls += ' h-1/4';
   } else {
      const newBtns = _.cloneDeep(simpleBtns);
      extraBtns.forEach((item) => {
         newBtns.splice(item.order, 0, item);
      });
      btns = newBtns;
      computeFunc = handleCompute;
      layoutCls += ' grid-cols-4';
      outerCls += ' h-1/3';
   }

   return (
      <div className={outerCls}>
         <div className={layoutCls}>
            {btns.map((item) => (
               <div
                  className="flex justify-center items-center"
                  onClick={computeFunc.bind(null, item.value, item.action)}
                  key={item.value}
               >
                  {item.title}
               </div>
            ))}
            {!isSimple && (
               <div
                  className="flex justify-center items-center bg-indigo-200"
                  onClick={handleFinish}
               >
                  {isOperate ? '=' : '完成'}
               </div>
            )}
         </div>
      </div>
   );
};
export default Caculator;
